import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
    // 写入用户数据到文件
    public static void writeUsersToFile(List<User> users, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(filePath), "UTF-8"))) {
            for (User user : users) {
                // 格式：userId,username,password(MD5),phone,userType
                writer.write(String.join(",",
                        user.getUserId(),
                        user.getUsername(),
                        user.getPassword(),
                        user.getPhone(),
                        user.getUserType().toString()
                ));
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("用户数据写入失败：" + e.getMessage());
        }
    }

// FileUtil.java 中修复用户读取逻辑
public static List<User> readUsersFromFile(String filePath) {
    List<User> users = new ArrayList<>();
    File file = new File(filePath);
    // 如果文件不存在，返回空列表（首次运行时正常）
    if (!file.exists()) {
        System.out.println("用户数据文件不存在，将使用初始数据");
        return users;
    }

    try (BufferedReader reader = new BufferedReader(
             new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
        String line;
        int lineNum = 0;
        while ((line = reader.readLine()) != null) {
            lineNum++;
            line = line.trim();
            if (line.isEmpty()) continue;

            String[] parts = line.split(",");
            // 严格校验格式：必须包含5个字段（userId,username,password,phone,userType）
            if (parts.length != 5) {
                System.err.println("用户数据格式错误（行" + lineNum + "）：" + line);
                continue; // 跳过错误行，避免影响其他数据
            }

            try {
                UserType userType = UserType.valueOf(parts[4].trim());
                User user = null;
                switch (userType) {
                    case ADMIN:
                        user = new Admin(parts[0].trim(), parts[1].trim(), parts[2].trim(), parts[3].trim());
                        break;
                    case MANAGER:
                        user = new Manager(parts[0].trim(), parts[1].trim(), parts[2].trim(), parts[3].trim());
                        break;
                    case RECEPTIONIST:
                        user = new Receptionist(parts[0].trim(), parts[1].trim(), parts[2].trim(), parts[3].trim());
                        break;
                }
                if (user != null) {
                    users.add(user);
                }
            } catch (IllegalArgumentException e) {
                System.err.println("用户类型错误（行" + lineNum + "）：" + parts[4]);
            }
        }
    } catch (IOException e) {
        System.err.println("读取用户数据失败：" + e.getMessage());
    }
    return users;
}

    // 写入影片数据到文件
    public static void writeMoviesToFile(List<Movie> movies, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(filePath), "UTF-8"))) {
            for (Movie movie : movies) {
                // 格式：movieId,name,director,actor,intro,duration,score
                writer.write(String.join(",",
                        movie.getMovieId(),
                        movie.getName(),
                        movie.getDirector(),
                        movie.getActor(),
                        movie.getIntro(),
                        String.valueOf(movie.getDuration()),
                        String.valueOf(movie.getScore())
                ));
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("影片数据写入失败：" + e.getMessage());
        }
    }

    // 从文件读取影片数据
    public static List<Movie> readMoviesFromFile(String filePath) {
        List<Movie> movies = new ArrayList<>();
        File file = new File(filePath);
        if (!file.exists()) return movies; // 文件不存在则返回空列表

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                new FileInputStream(filePath), "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",", 7); // 分割为7部分
                if (parts.length == 7) {
                    try {
                        Movie movie = new Movie(
                                parts[0],
                                parts[1],
                                parts[2],
                                parts[3],
                                parts[4],
                                Integer.parseInt(parts[5]),
                                Double.parseDouble(parts[6])
                        );
                        movies.add(movie);
                    } catch (Exception e) {
                        System.out.println("解析影片数据失败：" + line);
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("影片数据读取失败：" + e.getMessage());
        }
        return movies;
    }

    // 写入场次数据到文件
    public static void writeShowsToFile(List<Show> shows, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(filePath), "UTF-8"))) {
            for (Show show : shows) {
                // 格式：showId,movieId,hallName,time,price
                writer.write(String.join(",",
                        show.getShowId(),
                        show.getMovie().getMovieId(),
                        show.getHall().getHallName(),
                        show.getTime().toString(),
                        String.valueOf(show.getPrice())
                ));
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("场次数据写入失败：" + e.getMessage());
        }
    }

    // 从文件读取场次数据
    public static List<Show> readShowsFromFile(String filePath, List<Movie> movies, List<Hall> halls) {
        List<Show> shows = new ArrayList<>();
        File file = new File(filePath);
        if (!file.exists()) return shows; // 文件不存在则返回空列表

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                new FileInputStream(filePath), "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",", 5); // 分割为5部分
                if (parts.length == 5) {
                    try {
                        // 查找对应的影片
                        Movie movie = null;
                        for (Movie m : movies) {
                            if (m.getMovieId().equals(parts[1])) {
                                movie = m;
                                break;
                            }
                        }

                        // 查找对应的放映厅
                        Hall hall = null;
                        for (Hall h : halls) {
                            if (h.getHallName().equals(parts[2])) {
                                hall = h;
                                break;
                            }
                        }

                        if (movie != null && hall != null) {
                            Show show = new Show(
                                    parts[0],
                                    movie,
                                    hall,
                                    LocalDateTime.parse(parts[3]),
                                    Double.parseDouble(parts[4])
                            );
                            shows.add(show);
                        }
                    } catch (Exception e) {
                        System.out.println("解析场次数据失败：" + line);
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("场次数据读取失败：" + e.getMessage());
        }
        return shows;
    }

    // 写入票务数据到文件
    public static void writeTicketsToFile(List<Ticket> tickets, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(filePath), "UTF-8"))) {
            for (Ticket ticket : tickets) {
                // 格式：ticketId,showId,seats(行1,列1;行2,列2),price,isRefunded,sellTime
                StringBuilder seatsStr = new StringBuilder();
                for (Seat seat : ticket.getSeats()) {
                    if (seatsStr.length() > 0) seatsStr.append(";");
                    seatsStr.append(seat.getRow()).append(",").append(seat.getCol());
                }

                writer.write(String.join(",",
                        ticket.getTicketId(),
                        ticket.getShow().getShowId(),
                        seatsStr.toString(),
                        String.valueOf(ticket.getPrice()),
                        String.valueOf(ticket.isRefunded()),
                        ticket.getSellTime().toString()
                ));
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("票务数据写入失败：" + e.getMessage());
        }
    }

    // 从文件读取票务数据（简化实现，实际需关联场次）
    public static List<Ticket> readTicketsFromFile(String filePath) {
        // 注意：实际项目中需要结合场次数据才能完全恢复Ticket对象
        // 此处仅做基础读取，完整实现需传入ShowService
        return new ArrayList<>();
    }
}
    